package com.sgb.kjwl.view.ui.activity.self.publish;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.swgk.core.event.MessageEvent;
import com.sgb.kjwl.databinding.ActivityStDetailBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.AdmixtureEntity;
import com.sgb.kjwl.model.entity.Bean;
import com.sgb.kjwl.model.entity.ConcreteDetailEntity;
import com.sgb.kjwl.model.entity.ConcreteFilterEntity;
import com.sgb.kjwl.model.entity.GoodsSkuDetailEntity;
import com.sgb.kjwl.model.entity.STDetailEntity;
import com.sgb.kjwl.model.entity.StrengthEntity;
import com.sgb.kjwl.model.entity.StrengthEntity2;
import com.sgb.kjwl.model.entity.VideoEntity;
import com.sgb.kjwl.model.entity.user.ServerAttrValue;
import com.sgb.kjwl.model.entity.user.SkuItemAttrEntity;
import com.swgk.core.util.UiUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.GoodsEvent;
import com.sgb.kjwl.view.ui.adapter.material.GoodsSTAdapter;
import com.sgb.kjwl.view.ui.adapter.self.publish.DetailPzAdapter;
import com.sgb.kjwl.view.ui.adapter.self.publish.DetailServiceAdapter;
import com.sgb.kjwl.view.ui.adapter.self.publish.DetailStrengthAdapter;
import com.sgb.kjwl.view.ui.adapter.self.publish.DetailWjjAdapter;
import com.sgb.kjwl.view.ui.adapter.shopping.AttrAdapter;
import com.sgb.kjwl.view.ui.adapter.shopping.IndicatorAdapter;
import com.sgb.kjwl.view.widget.GoodSAttributeWindow;
import com.sgb.kjwl.view.widget.GoodSSTWindow;
import com.sgb.kjwl.view.widget.GoodsDetailPriceDialog3;
import com.sgb.kjwl.viewmodel.self.publish.STDetailModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.CommonDialog;
import com.zhy.view.flowlayout.TagAdapter;

import org.apache.commons.lang3.StringEscapeUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.nodes.Document;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import cn.jzvd.Jzvd;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

import static com.swgk.core.event.EventConstant.EVENT_GOODS_PUBLISH;
import static com.sgb.kjwl.view.widget.GoodSSTWindow.TYPE_SELF;

/**
 * 商砼详情（我的-商品报价-商品列表）
 *
 * @author 陈方凯
 */
public class STDetailActivity extends AppActivity {
    private ActivityStDetailBinding binding;
    private String id;
    private String arr = "";
    private DetailStrengthAdapter detailStrengthAdapter;
    private DetailWjjAdapter wjjAdapter;
    private DetailServiceAdapter detailServiceAdapter;
    private DetailPzAdapter detailPzAdapter;
    //视频
    private SensorManager sensorManager;
    private SensorEventListener sensorEventListener;
    private int selectPosition = -1;
    //被选中的强度等级价格
    private String priceS = "0.00";
    //计算价格
    private BigDecimal bigDecimal;
    //总价格
    private String allPrice;
    //service价格
    private String servicePrice = "0.00";
    //配置价格
    private String pzPrice = "0.00";
    //保存外加剂选中的下标
    private Map map;
    //保存多选的数据
    private Map mapData;
    //外加剂 原始数据
    private List<StrengthEntity2> childList;

    private GoodSSTWindow goodSSTWindow;
    private GoodSAttributeWindow goodSAttributeWindow;
    private GoodsSTAdapter goodsSTAdapter;
    //被选中的外加剂数据
    private List<StrengthEntity2> strengthEntity2sAll;
    private int mLastIndex;
    List<String> videos = new ArrayList<>();
    private int itemNum = 1;
    private boolean isFirst;
    private boolean isShowFirstAttrWindow;
    ConcreteDetailEntity entity;
    private ArrayList<String> mSelect = new ArrayList<>();
    private AttrAdapter mAttrAdapter;
    Document htmlResult;
    @Inject
    STDetailModel viewModel;
    public static final String OPT_UP = "1";
    public static final String OPT_DOWN = "2";
    public static final String OPT_DEL = "3";
    private String[] titls = new String[]{"商品详情", "其他信息"};

    public static void start(Context context, String id) {
        Intent intent = new Intent(context, STDetailActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(STDetailActivity.this, R.layout.activity_st_detail);
        binding.setViewModel(viewModel);
        binding.tvEdit.setOnClickListener(this);
        binding.modifyLayout.setOnClickListener(this);
        binding.upLayout.setOnClickListener(this);
        binding.delLayout.setOnClickListener(this);
        binding.downLayout.setOnClickListener(this);
        binding.backView.setOnClickListener(this);
        binding.backViewToolBar.setOnClickListener(this);
        binding.rlGg.setOnClickListener(this);
        binding.rlAtr.setOnClickListener(this);
        setToolBar();
        goodSSTWindow = new GoodSSTWindow(STDetailActivity.this, TYPE_SELF);
        goodSSTWindow.setBgView(binding.grayLayout);
        goodSSTWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                itemNum = Integer.parseInt((String) key1);
            }
        });

        goodSAttributeWindow = new GoodSAttributeWindow(STDetailActivity.this);
        goodSAttributeWindow.setBgView(binding.grayLayout);
        goodSAttributeWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
            }
        });
        binding.tablayout2.addTab(binding.tablayout2.newTab().setText(titls[0]));
        binding.tablayout2.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (binding.llWv.getChildCount() > 0) {
                    binding.llWv.removeAllViews();
                }
                if (tab.getPosition() == 0) {
                    // TODO: 2020/12/15 0015
                    if (viewModel.stDetailEntity.get() != null && !TextUtils.isEmpty(viewModel.stDetailEntity.get().getItemDetail())) {
                        setHtml(viewModel.stDetailEntity.get().getItemDetail());
                    } else {
                        binding.empty.setVisibility(View.VISIBLE);
                    }
                    if (viewModel.stDetailEntity.get().getVideoList() != null && videos.size() > 0) {
                        binding.flVideo.setVisibility(View.VISIBLE);
                        binding.empty.setVisibility(View.GONE);
                    }
                } else {
                    binding.flVideo.setVisibility(View.GONE);
                    binding.empty.setVisibility(View.GONE);
                    showWebView(StringEscapeUtils.unescapeJava(viewModel.stDetailEntity.get().getItemTitleUrl()));
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {


            }
        });


    }

    /**
     * 初始化setToolBar
     */
    private void setToolBar() {
        binding.appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                binding.toolbar.setBackgroundColor(changeAlpha(getResources().getColor
                        (R.color.new_blue), Math.abs(verticalOffset * 1.0f) / appBarLayout.getTotalScrollRange()));
                binding.toolbar.setAlpha(Math.abs(verticalOffset * 1.0f) / appBarLayout
                        .getTotalScrollRange());
            }
        });
    }

    /**
     * 根据百分比改变颜色透明度
     */
    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

    @Override
    protected void init() {
        id = getIntent().getStringExtra("id");
        viewModel.getGoodsDetail(id);
        map = new HashMap();
        mapData = new HashMap();
        childList = new ArrayList<>();
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new JCVideoPlayer.JCAutoFullscreenListener();
    }

    public void initData() {
        if (!TextUtils.isEmpty(viewModel.stDetailEntity.get().getItemTitleUrl())) {
            if (binding.tablayout2.getTabCount() == 1) {
                binding.tablayout2.addTab(binding.tablayout2.newTab().setText(titls[1]));
            }
        } else {
            binding.tablayout2.setVisibility(View.GONE);
            binding.tvDetail.setVisibility(View.VISIBLE);
        }
        binding.tvStatus.setText(viewModel.stDetailEntity.get().getStatus());
        if (viewModel.stDetailEntity.get().getStatus().equals("已上架")) {
            binding.tvStatus.setBackground(getResources().getDrawable(R.drawable.corner_blue_shape));
            binding.upLayout.setVisibility(View.GONE);
            binding.tvEdit.setTextColor(getResources().getColor(R.color.new_blue_50));
            binding.downLayout.setVisibility(View.VISIBLE);
        } else {
            binding.tvStatus.setBackground(getResources().getDrawable(R.drawable.corner_gray_shape));
            binding.upLayout.setVisibility(View.VISIBLE);
            binding.downLayout.setVisibility(View.GONE);
            binding.tvEdit.setTextColor(getResources().getColor(R.color.new_blue));
        }
        initBanner(viewModel.stDetailEntity.get());
        videos(viewModel.stDetailEntity.get());
        setGoodsOtherService(viewModel.stDetailEntity.get());
        setHtml(viewModel.stDetailEntity.get().getItemDetail());

//         List<SingleEntity> singleEntityList = new ArrayList<SingleEntity>();
//        SingleEntity strengthEntity = new SingleEntity();
//        strengthEntity.setKey("强度等级");
//        String strengthList = "";
//        for (int i = 0; i < viewModel.stDetailEntity.get().getStrengthList().getChildList().size(); i++) {
//            strengthList += "、" + viewModel.stDetailEntity.get().getStrengthList().getChildList().get(i).getName();
//        }
//        if (strengthList.length() > 0) {
//            strengthEntity.setValue(strengthList.substring(1));
//        }
//        singleEntityList.add(strengthEntity);
//
//        SingleEntity admixtureListEntity = new SingleEntity();
//        admixtureListEntity.setKey("外加剂");
//        String admixtureList = "";
//
//        for (int i = 0; i < viewModel.stDetailEntity.get().getAdmixtureList().getChildList().size(); i++) {
//            admixtureList += "、" + viewModel.stDetailEntity.get().getAdmixtureList().getChildList().get(i).getName();
//        }
//        if (admixtureList.length() > 0) {
//            admixtureListEntity.setValue(admixtureList.substring(1));
//        }
//        singleEntityList.add(admixtureListEntity);
//
//        SingleEntity serviceListEntity = new SingleEntity();
//        serviceListEntity.setKey("服务");
//        String serviceList = "";
//        for (int i = 0; i < viewModel.stDetailEntity.get().getServiceList().getChildList().size(); i++) {
//            serviceList += "、" + viewModel.stDetailEntity.get().getServiceList().getChildList().get(i).getName();
//        }
//        if (serviceList.length() > 0) {
//            serviceListEntity.setValue(serviceList.substring(1));
//        }
//        singleEntityList.add(serviceListEntity);
//
//        SingleEntity gradationListEntity = new SingleEntity();
//        gradationListEntity.setKey("配置");
//        String gradationList = "";
//        for (int i = 0; i < viewModel.stDetailEntity.get().getGradationList().getChildList().size(); i++) {
//            gradationList += "、" + viewModel.stDetailEntity.get().getGradationList().getChildList().get(i).getName();
//        }
//        if (gradationList.length() > 0) {
//            gradationListEntity.setValue(gradationList.substring(1));
//        }
//        singleEntityList.add(gradationListEntity);
//        binding.tvArr.setText("强度等级、外加剂、服务、配置");
        StringBuffer stringBuffer = new StringBuffer();
        if (viewModel.stDetailEntity.get().getStrengthList() != null && viewModel.stDetailEntity.get().getStrengthList().getChildList() != null && viewModel.stDetailEntity.get().getStrengthList().getChildList().size() > 0) {
            stringBuffer.append("强度等级、");
        }
        if (viewModel.stDetailEntity.get().getAdmixtureList() != null && viewModel.stDetailEntity.get().getAdmixtureList().getChildList() != null && viewModel.stDetailEntity.get().getAdmixtureList().getChildList().size() > 0) {
            stringBuffer.append("外加剂、");
        }
        if (viewModel.stDetailEntity.get().getServiceList() != null && viewModel.stDetailEntity.get().getServiceList().getChildList() != null && viewModel.stDetailEntity.get().getServiceList().getChildList().size() > 0) {
            stringBuffer.append("服务、");
        }
        if (viewModel.stDetailEntity.get().getGradationList() != null && viewModel.stDetailEntity.get().getGradationList().getChildList() != null && viewModel.stDetailEntity.get().getGradationList().getChildList().size() > 0) {
            stringBuffer.append("配置、");
        }
        binding.tvArr.setText(stringBuffer.substring(0, stringBuffer.length() - 1));
        entity = new ConcreteDetailEntity();
        entity.setTitle(viewModel.stDetailEntity.get().getTitle());
        List<AdmixtureEntity> admixtureLists = new ArrayList<>();
        if (viewModel.stDetailEntity.get().getAdmixtureList() != null && viewModel.stDetailEntity.get().getAdmixtureList().getChildList() != null) {
            for (int i = 0; i < viewModel.stDetailEntity.get().getAdmixtureList().getChildList().size(); i++) {
                StrengthEntity2 strengthEntity2 = viewModel.stDetailEntity.get().getAdmixtureList().getChildList().get(i);
                AdmixtureEntity admixtureEntity = new AdmixtureEntity();
                admixtureEntity.setAdmixtureName(strengthEntity2.getName());
                List<ConcreteFilterEntity> concreteFilterEntities = new ArrayList<>();
                for (int j = 0; j < strengthEntity2.getSpec().size(); j++) {
                    StrengthEntity strengthEntity1 = strengthEntity2.getSpec().get(j);
                    ConcreteFilterEntity entity2 = new ConcreteFilterEntity();
                    entity2.setId(strengthEntity1.getId());
                    entity2.setPrice(strengthEntity1.getPrice());
                    entity2.setName(strengthEntity1.getSpec());
                    concreteFilterEntities.add(entity2);
                }
                admixtureEntity.setSpec(concreteFilterEntities);
                admixtureLists.add(admixtureEntity);
            }
        }
        entity.setAdmixtureList(admixtureLists);

        List<ConcreteFilterEntity> strengthLists = new ArrayList<>();
        if (viewModel.stDetailEntity.get().getStrengthList() != null && viewModel.stDetailEntity.get().getStrengthList().getChildList() != null) {
            for (int i = 0; i < viewModel.stDetailEntity.get().getStrengthList().getChildList().size(); i++) {
                StrengthEntity strengthEntity1 = viewModel.stDetailEntity.get().getStrengthList().getChildList().get(i);
                ConcreteFilterEntity concreteFilterEntity = new ConcreteFilterEntity();
                concreteFilterEntity.setName(strengthEntity1.getName());
                concreteFilterEntity.setPrice(strengthEntity1.getPrice());
                concreteFilterEntity.setId(strengthEntity1.getId());
                strengthLists.add(concreteFilterEntity);
            }
        }
        entity.setStrengthList(strengthLists);

        List<ConcreteFilterEntity> serviceLists = new ArrayList<>();
        if (viewModel.stDetailEntity.get().getServiceList() != null && viewModel.stDetailEntity.get().getServiceList().getChildList() != null) {
            for (int i = 0; i < viewModel.stDetailEntity.get().getServiceList().getChildList().size(); i++) {
                StrengthEntity strengthEntity1 = viewModel.stDetailEntity.get().getServiceList().getChildList().get(i);
                ConcreteFilterEntity concreteFilterEntity = new ConcreteFilterEntity();
                concreteFilterEntity.setName(strengthEntity1.getName());
                concreteFilterEntity.setPrice(strengthEntity1.getPrice());
                concreteFilterEntity.setId(strengthEntity1.getId());
                serviceLists.add(concreteFilterEntity);
            }
        }
        entity.setServiceList(serviceLists);
        entity.setItemTitleUrl(viewModel.stDetailEntity.get().getItemTitleUrl());
        List<ConcreteFilterEntity> gradationLists = new ArrayList<>();
        if (viewModel.stDetailEntity.get().getGradationList() != null && viewModel.stDetailEntity.get().getGradationList().getChildList() != null) {
            for (int i = 0; i < viewModel.stDetailEntity.get().getGradationList().getChildList().size(); i++) {
                StrengthEntity strengthEntity1 = viewModel.stDetailEntity.get().getGradationList().getChildList().get(i);
                ConcreteFilterEntity concreteFilterEntity = new ConcreteFilterEntity();
                concreteFilterEntity.setName(strengthEntity1.getName());
                concreteFilterEntity.setPrice(strengthEntity1.getPrice());
                concreteFilterEntity.setId(strengthEntity1.getId());
                gradationLists.add(concreteFilterEntity);
            }
        }
        entity.setGradationList(gradationLists);
//        detailStrengthAdapter.setDatas(viewModel.stDetailEntity.get().getStrengthList().getChildList());
//        detailStrengthAdapter.setDefItem(0);
//        if (viewModel.stDetailEntity.get().getStrengthList().getChildList() != null && viewModel.stDetailEntity.get().getStrengthList().getChildList().size() > 0) {
//            priceS = viewModel.stDetailEntity.get().getStrengthList().getChildList().get(0).getPrice();
//        }
//        calculation(viewModel.stDetailEntity.get().getPrice(), priceS, servicePrice, pzPrice, strengthEntity2sAll);
//        if (viewModel.stDetailEntity.get().getAdmixtureList().getChildList() == null || viewModel.stDetailEntity.get().getAdmixtureList().getChildList().size() == 0) {
//            binding.llWjj.setVisibility(View.GONE);
//        } else {
//            wjjAdapter.setDatas(viewModel.stDetailEntity.get().getAdmixtureList().getChildList());
//        }
//        if (viewModel.stDetailEntity.get().getServiceList().getChildList().size() == 1) {
//            detailServiceAdapter.setDefItem(0);
//        } else {
//            detailServiceAdapter.setDefItem(-1);
//        }
//        detailServiceAdapter.setDatas(viewModel.stDetailEntity.get().getServiceList().getChildList());
//        if (viewModel.stDetailEntity.get().getServiceList().getChildList().size() == 1) {
//            detailPzAdapter.setDefItem(0);
//        } else {
//            detailPzAdapter.setDefItem(-1);
//        }
//        detailPzAdapter.setDatas(viewModel.stDetailEntity.get().getGradationList().getChildList());
//       /* for (int i = 0;i<viewModel.stDetailEntity.get().getAdmixtureList().getChildList().size();i++){
//            StrengthEntity2 strengthEntity2 = new StrengthEntity2();
//            strengthEntity2 = viewModel.stDetailEntity.get().getAdmixtureList().getChildList().get(i);
//            childList.add(strengthEntity2);
//        }*/
//        childList.addAll(viewModel.stDetailEntity.get().getAdmixtureList().getChildList());
    }

    /**
     * 商品其他服务
     *
     * @param stDetailEntity
     */
    private void setGoodsOtherService(STDetailEntity stDetailEntity) {
        List<ServerAttrValue> itemServerAttrVals = stDetailEntity.getItemServerAttrVals();
        if (itemServerAttrVals == null || itemServerAttrVals.size() == 0) {
            return;
        }
        for (ServerAttrValue attrValue : itemServerAttrVals) {
            if (attrValue.getServiceType() == 1) {
                List<ServerAttrValue.GoodsServiceOtherAttr> attrValueValue = attrValue.getValue();
                if (attrValueValue != null && attrValueValue.size() != 0) {
                    setGoodsOtherService(attrValueValue);
                }
                break;
            }
        }
    }

    private void setGoodsOtherService(List<ServerAttrValue.GoodsServiceOtherAttr> attrList) {
        List<ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue> attrValueArrayList = new ArrayList<>();
        for (ServerAttrValue.GoodsServiceOtherAttr otherAttrValue : attrList) {
            List<ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue> otherAttrValueValue = otherAttrValue.getValue();
            if (otherAttrValueValue != null && otherAttrValueValue.size() != 0) {
                for (ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue oav : otherAttrValueValue) {
                    if (oav.getChecked() == 1) {
                        attrValueArrayList.add(oav);
                    }
                }
            }
        }
        if (attrValueArrayList.size() > 0) {
            binding.tagContainer.setVisibility(View.VISIBLE);
            showGoodsOtherService(attrValueArrayList);
        }
    }

    private void showGoodsOtherService(List<ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue> attrValueArrayList) {
        TagAdapter<ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue> attrAdapter = new TagAdapter<ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue>(attrValueArrayList) {
            @Override
            public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue otherAttrValue) {
                final LayoutInflater mInflater = LayoutInflater.from(STDetailActivity.this);
                LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_goods_service_other, binding.tagContainer, false);
                TextView tv = layout.findViewById(R.id.item_attr);
                tv.setText(otherAttrValue.getAttributeName());
                return layout;
            }
        };
        binding.tagContainer.setAdapter(attrAdapter);
    }

    public void showPrice(String totalPrice) {
        binding.tvPrice.setText(totalPrice);
    }

    public void setYXGG(String content) {
        mSelect.clear();
        for (String s : content.split("、")) {
            mSelect.add(s);
        }
        binding.rvSelect.setLayoutManager(new LinearLayoutManager(UiUtil.getContext(), RecyclerView.HORIZONTAL, false));
        mAttrAdapter = new AttrAdapter(mSelect);
        binding.llSelect.setVisibility(View.VISIBLE);
        binding.rvSelect.setAdapter(mAttrAdapter);
        // TODO: 2020/12/17 0017
        // TODO: 2020/12/17 0017
        // TODO: 2020/12/17 0017
    }

    private void calculation(String price, String strength, String service, String pz, List<StrengthEntity2> strengthEntity2s) {
        bigDecimal = new BigDecimal("0.00");
        BigDecimal wjjB = new BigDecimal("0.00");
        if (strengthEntity2s != null) {
            for (int i = 0; i < strengthEntity2s.size(); i++) {
                for (int j = 0; j < strengthEntity2s.get(i).getSpec().size(); j++) {
                    if (strengthEntity2s.get(i).isHaveSpec()) {
                        if (strengthEntity2s.get(i).getSpec().get(j).isIsselect() == true) {
                            BigDecimal allB = new BigDecimal(strengthEntity2s.get(i).getSpec().get(j).getPrice());
                            wjjB = wjjB.add(allB);
                        }
                    } else {
                        BigDecimal allB = new BigDecimal(strengthEntity2s.get(i).getSpec().get(j).getPrice());
                        wjjB = wjjB.add(allB);
                    }
                }
            }
        }
        //     BigDecimal priceB = new BigDecimal(price);
        BigDecimal strengthB = new BigDecimal(strength);
        BigDecimal serviceB = new BigDecimal(service);
        BigDecimal pzB = new BigDecimal(pz);
        bigDecimal =/* priceB.add(strengthB)*/
                strengthB.add(serviceB)
                        .add(pzB)
                        .add(wjjB);
        binding.tvPrice.setText(bigDecimal.toString());
    }

//    public void showWjjPop(List<StrengthEntity> spec, int position) {
//        //条件选择器
//        CityPickView cityOption = new CityPickBuilder(STDetailActivity.this, (options1, options2, options3, v) -> {
//            map.put(position, options1);
//            wjjAdapter.getDatas().get(position).setName(spec.get(options1).getSpec());
//            wjjAdapter.setArrName(spec.get(options1).getSpec(), position, true);
//            wjjAdapter.getDatas().get(position).getSpec().get(options1).setIsselect(true);
//            calculation(viewModel.stDetailEntity.get().getPrice(), priceS, servicePrice, pzPrice, strengthEntity2sAll);
//        }).build();
//        cityOption.setPicker(spec);
//        if (map.size() == 0) {
//            cityOption.setSelectOptions(0);
//        } else if ((Integer) map.get(position) != null) {
//            cityOption.setSelectOptions((Integer) map.get(position));
//        }
//
//        cityOption.show();
//    }

    public void setHtml(String htmls) {
        if (!TextUtils.isEmpty(htmls)) {
            binding.empty.setVisibility(View.GONE);
            binding.llWv.removeAllViews();
            WebView webView1 = new WebView(STDetailActivity.this);
            WebSettings webSettings = webView1.getSettings();
            webSettings.setUseWideViewPort(true);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            binding.llWv.setVisibility(View.VISIBLE);
            webView1.setHorizontalScrollBarEnabled(false);
            webView1.setVerticalScrollBarEnabled(false);
            webView1.loadDataWithBaseURL(null, setWebViewContent(htmls), "text/html", "UTF-8", null);
            webView1.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            webView1.measure(0, 0);
                            int measuredHeight = webView1.getMeasuredHeight();
                            ViewGroup.LayoutParams layoutParams = webView1.getLayoutParams();
                            layoutParams.height = measuredHeight;
                            webView1.setLayoutParams(layoutParams);
                        }
                    }, 1000);
                }
            });
            webView1.requestLayout();
            binding.llWv.addView(webView1);
            webView1.requestLayout();
        } else {
            binding.llWv.setVisibility(View.GONE);
        }
    }

    private String setWebViewContent(String content) {
        String head = "<style type=\"text/css\"> img {" +
                "width:100%;" +//限定图片宽度填充屏幕
                "height:auto;" +//限定图片高度自动
                "}" +
                "body {" +
                "margin-right:15px;" +//限定网页中的文字右边距为15px(可根据实际需要进行行管屏幕适配操作)
                "margin-left:15px;" +//限定网页中的文字左边距为15px(可根据实际需要进行行管屏幕适配操作)
                "margin-top:15px;" +//限定网页中的文字上边距为15px(可根据实际需要进行行管屏幕适配操作)
                "font-size:38px;" +//限定网页中文字的大小为40px,请务必根据各种屏幕分辨率进行适配更改
                "word-wrap:break-word;" +//允许自动换行(汉字网页应该不需要这一属性,这个用来强制英文单词换行,类似于word/wps中的西文换行)
                "}" +
                "</style>";
        return "<html><header>" + head + "</header>" + content + "</html>";
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoodsEvent(GoodsEvent event) {
        if (event.getMessageTag() == EVENT_GOODS_PUBLISH) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    viewModel.getGoodsDetail(id);
                }
            }, 3000);//3秒后执行Runnable中的run方法

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.modify_layout:
                modifyGoodsPrice();
                break;
            case R.id.up_layout:
                getGoodsIds(OPT_UP);
                break;
            case R.id.down_layout:
                getGoodsIds(OPT_DOWN);
                break;
            case R.id.del_layout:
                getGoodsIds(OPT_DEL);
                break;
            case R.id.tv_edit:
//                Toast.makeText(STDetailActivity.this,"功能暂未开放",Toast.LENGTH_SHORT).show();
                if (!"已上架".equals(viewModel.stDetailEntity.get().getStatus()))
                    GoodsPublishActivity.start(STDetailActivity.this, id, true);
//                GoodsPublishActivity.start(STDetailActivity.this);
                break;
            case R.id.back_view:
            case R.id.back_view_tool_bar:
                if (JCVideoPlayer.backPress()) {
                    return;
                }
                finish();
                break;
            case R.id.rl_gg:
                if (viewModel.stDetailEntity.get() == null) return;
                showSTPop();
                break;
            case R.id.rl_atr:
                if (viewModel.stDetailEntity.get() == null) return;
                showAttrPop();
                break;
        }
    }

    //产品规格弹窗展示
    private void showSTPop() {
        if (!isFirst) {
            goodSSTWindow.setData(entity);
            isFirst = true;
        }
        goodSSTWindow.showDownPopwindow(binding.grayLayout, true);
    }

    private void showAttrPop() {
        if (!isShowFirstAttrWindow) {
            isShowFirstAttrWindow = true;
            List<SkuItemAttrEntity> getSku = new ArrayList<>();
            if (viewModel.stDetailEntity.get().getStrengthList() != null && viewModel.stDetailEntity.get().getStrengthList().getChildList() != null && viewModel.stDetailEntity.get().getStrengthList().getChildList().size() > 0) {
                SkuItemAttrEntity skuItemAttrEntity1 = new SkuItemAttrEntity();
                skuItemAttrEntity1.setParamData("强度等级");
                List<SkuItemAttrEntity.Child> singleEntityList = new ArrayList<>();
                for (int i = 0; i < viewModel.stDetailEntity.get().getStrengthList().getChildList().size(); i++) {
                    SkuItemAttrEntity.Child child = new SkuItemAttrEntity.Child();
                    child.setValData(viewModel.stDetailEntity.get().getStrengthList().getChildList().get(i).getName());
                    singleEntityList.add(child);
                }
                skuItemAttrEntity1.setList(singleEntityList);
                getSku.add(skuItemAttrEntity1);
            }

            if (viewModel.stDetailEntity.get().getAdmixtureList() != null && viewModel.stDetailEntity.get().getAdmixtureList().getChildList() != null && viewModel.stDetailEntity.get().getAdmixtureList().getChildList().size() > 0) {
                SkuItemAttrEntity skuItemAttrEntity2 = new SkuItemAttrEntity();
                skuItemAttrEntity2.setParamData("外加剂");
                List<SkuItemAttrEntity.Child> admixtureListEntity = new ArrayList<>();
                for (int i = 0; i < viewModel.stDetailEntity.get().getAdmixtureList().getChildList().size(); i++) {
                    SkuItemAttrEntity.Child child = new SkuItemAttrEntity.Child();
                    child.setValData(viewModel.stDetailEntity.get().getAdmixtureList().getChildList().get(i).getName());
                    admixtureListEntity.add(child);
                }
                skuItemAttrEntity2.setList(admixtureListEntity);
                getSku.add(skuItemAttrEntity2);
            }


            if (viewModel.stDetailEntity.get().getServiceList() != null && viewModel.stDetailEntity.get().getServiceList().getChildList() != null && viewModel.stDetailEntity.get().getServiceList().getChildList().size() > 0) {
                SkuItemAttrEntity skuItemAttrEntity3 = new SkuItemAttrEntity();
                skuItemAttrEntity3.setParamData("服务");
                List<SkuItemAttrEntity.Child> serviceListEntity = new ArrayList<>();
                for (int i = 0; i < viewModel.stDetailEntity.get().getServiceList().getChildList().size(); i++) {
                    SkuItemAttrEntity.Child child = new SkuItemAttrEntity.Child();
                    child.setValData(viewModel.stDetailEntity.get().getServiceList().getChildList().get(i).getName());
                    serviceListEntity.add(child);
                }
                skuItemAttrEntity3.setList(serviceListEntity);
                getSku.add(skuItemAttrEntity3);
            }
            if (viewModel.stDetailEntity.get().getGradationList() != null && viewModel.stDetailEntity.get().getGradationList().getChildList() != null && viewModel.stDetailEntity.get().getGradationList().getChildList().size() > 0) {
                SkuItemAttrEntity skuItemAttrEntity4 = new SkuItemAttrEntity();
                skuItemAttrEntity4.setParamData("配置");
                List<SkuItemAttrEntity.Child> gradationListEntity = new ArrayList<>();
                for (int i = 0; i < viewModel.stDetailEntity.get().getGradationList().getChildList().size(); i++) {
                    SkuItemAttrEntity.Child child = new SkuItemAttrEntity.Child();
                    child.setValData(viewModel.stDetailEntity.get().getGradationList().getChildList().get(i).getName());
                    gradationListEntity.add(child);
                }
                skuItemAttrEntity4.setList(gradationListEntity);
                getSku.add(skuItemAttrEntity4);
            }
            GoodsSkuDetailEntity data = new GoodsSkuDetailEntity();
            GoodsSkuDetailEntity.ItemAttr itemAttr = new GoodsSkuDetailEntity.ItemAttr();
            itemAttr.setSku(getSku);
            data.setItemAttr(itemAttr);
            goodSAttributeWindow.setData(data);
        }
        goodSAttributeWindow.showDownPopwindow(binding.grayLayout, true);
    }


    private void getGoodsIds(String opt) {
        List<String> goodsIds = new ArrayList<>();
        goodsIds.add(viewModel.stDetailEntity.get().getId());
        if (opt.equals(OPT_UP)) {
            String msg = "商品即将上架对外销售";
            new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                    .setTitle("温馨提示")
                    .setMsg(msg)
                    .setDialogCallBack(new CommonDialog.DialogCallBack() {
                        @Override
                        public void onRightClick() {
                            viewModel.upDowngetGoodsModel(opt, goodsIds);
                        }

                        @Override
                        public void onLeftClick() {

                        }
                    }).show();
        } else if (opt.equals(OPT_DOWN)) {
            String msg = "商品下架后，将不在平台出售";
            new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                    .setTitle("温馨提示")
                    .setMsg(msg)
                    .setDialogCallBack(new CommonDialog.DialogCallBack() {
                        @Override
                        public void onRightClick() {
                            viewModel.upDowngetGoodsModel(opt, goodsIds);
                        }

                        @Override
                        public void onLeftClick() {

                        }
                    }).show();
        } else if (opt.equals(OPT_DEL)) {
            String msg = "删除不可恢复，是否确定删除？";
            new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                    .setTitle("温馨提示")
                    .setMsg(msg)
                    .setDialogCallBack(new CommonDialog.DialogCallBack() {
                        @Override
                        public void onRightClick() {
                            viewModel.upDowngetGoodsModel(opt, goodsIds);
                        }

                        @Override
                        public void onLeftClick() {

                        }
                    }).show();
        }
    }

    private void modifyGoodsPrice() {
        new GoodsDetailPriceDialog3(getActivity(), null)
                .setPrice(viewModel.stDetailEntity.get().getPrice())
                .setUnit("立方米")
                .setDialogClickCallBack(new GoodsDetailPriceDialog3.DialogClickCallBack() {
                    @Override
                    public void onClickResult(String price) {
                        viewModel.modifyGoodsDetailPriceModel(viewModel.stDetailEntity.get().getId(), price);
                    }
                }).show();
    }

    public void optSuccess(String opt) {
        if (opt.equals(OPT_UP)) {
            viewModel.getGoodsDetail(id);
        } else if (opt.equals(OPT_DOWN)) {
            viewModel.getGoodsDetail(id);
        } else if (opt.equals(OPT_DEL)) {
            EventBus.getDefault().post(GoodsEvent.make().setMessageTag(EventConstant.EVENT_GOODS_PUBLISH_NO_ID));
            finish();
        }
    }

    public void modifySuccess() {
        viewModel.getGoodsDetail(id);
    }

    //banner
    private void initBanner(STDetailEntity data) {
        // 轮播图
        List<String> urls = new ArrayList<>();
        List<Bean> indicator = new ArrayList<>();
        boolean isHasVideo = false;
        if (data.getVideoList() != null && data.getVideoList().size() > 0) {
            for (int i = 0; i < data.getVideoList().size(); i++) {
                if (data.getVideoList().get(i).type == 1) {
                    String key = "视频";
                    String video = data.getVideoList().get(i).playUrl + key +
                            data.getVideoList().get(i).playUrlImg + key +
                            data.getVideoList().get(i).time + key
                            + data.getVideoList().get(i).videoName;
                    urls.add(video);
                    if (TextUtils.isEmpty(data.getVideoList().get(i).playUrlImg)) {
                        isHasVideo = true;
                        indicator.add(new Bean(data.getVideoList().get(i).playUrl, 1));
                    } else {
                        indicator.add(new Bean(data.getVideoList().get(i).playUrlImg, 1));
                    }
                }
            }
        }
        binding.rv.setLayoutManager(new LinearLayoutManager(UiUtil.getContext(), RecyclerView.HORIZONTAL, false));
        for (String img : data.getImages()) {
            indicator.add(new Bean(img, 0));
            urls.add(img);
        }
        indicator.get(0).select = true;
        IndicatorAdapter adapter = new IndicatorAdapter(indicator);
        adapter.setIsHasVideo(isHasVideo);
        binding.rv.setAdapter(adapter);
        binding.tvPosition.setText(1 + "");
        binding.tvCount.setText(indicator.size() + "");
        binding.banner.initBannerImageView(urls, false, false, 0);
        binding.banner.onSel(index -> {
            if (mLastIndex == index) {
                return;
            }
            if (index != 0) {
                Jzvd.releaseAllVideos();
            }
            binding.tvPosition.setText(index + 1 + "");
            adapter.getData().get(index).select = true;
            adapter.getData().get(mLastIndex).select = false;
            mLastIndex = index;
            adapter.notifyDataSetChanged();
        });
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            if (mLastIndex == position) {
                return;
            }
            if (position != 0) {
                Jzvd.releaseAllVideos();
            }
            binding.tvPosition.setText(position + 1 + "");
            binding.tvCount.setText(indicator.size() + "");
            binding.banner.mRecyclerView.scrollToPosition(position);
            adapter.getData().get(position).select = true;
            adapter.getData().get(mLastIndex).select = false;
            mLastIndex = position;
            adapter.notifyDataSetChanged();
        });
    }

    private void videos(STDetailEntity data) {
        // NormalRecyclerAdapter 视频和图片处理
        videos.clear();
        if (data.getVideoList() != null && data.getVideoList().size() != 0) {
            for (VideoEntity videoBean : data.getVideoList()) {
                if (videoBean.type != 1) {
                    videos.add(videoBean.playUrl + "视频" + videoBean.playUrlImg);
                }
            }
        }
        binding.tvPos.setText(1 + "");
        binding.tvSum.setText(videos.size() + "");
        binding.flVideo.setVisibility(videos.size() == 0 ? View.GONE : View.VISIBLE);
        binding.empty.setVisibility(videos.size() == 0 ? View.VISIBLE : View.GONE);
        binding.bannerVideo.initBannerImageView(videos, true, false, 1);
        binding.bannerVideo.onSel(index -> binding.tvPos.setText(index + 1 + ""));
    }

    @Subscribe
    public void getCode(MessageEvent event) {
        switch (event.code) {
            case EventConstant
                    .EVENT_STATE:
                int state = (int) event.data;
                binding.rv.setVisibility((state == 0 || state == 7) ? View.VISIBLE : View.GONE);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    private void showWebView(String link) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(link)) {
                    WebView webView2 = new WebView(STDetailActivity.this);
                    webView2.setFocusable(true);
                    webView2.setFocusableInTouchMode(true);
                    WebSettings webSettings = webView2.getSettings();
                    if (Build.VERSION.SDK_INT >= 19) {
                        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                    }
                    webSettings.setJavaScriptEnabled(true);
                    webSettings.setDomStorageEnabled(true);
                    webSettings.setAppCacheEnabled(false);
                    binding.llWv.setVisibility(View.VISIBLE);
                    webView2.setWebViewClient(new WebViewClient() {
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            view.loadUrl(url);
                            return super.shouldOverrideUrlLoading(view, url);
                        }
                    });
                    webView2.loadUrl(StringEscapeUtils.unescapeJava(link));
                    webView2.requestLayout();
                    binding.llWv.addView(webView2);
                    webView2.setWebViewClient(new WebViewClient() {

                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            view.loadUrl(url);
                            return super.shouldOverrideUrlLoading(view, url);
                        }

                        @Override
                        public void onPageFinished(WebView view, String url) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    webView2.measure(0, 0);
                                    int measuredHeight = webView2.getMeasuredHeight();
                                    ViewGroup.LayoutParams layoutParams = webView2.getLayoutParams();
                                    layoutParams.height = measuredHeight;
                                    webView2.setLayoutParams(layoutParams);
                                }
                            }, 1000);
                        }
                    });
                    webView2.requestLayout();
                } else {
                    binding.llWv.setVisibility(View.GONE);
                }
            }
        });
    }
}
